import React, {useEffect, useRef, useState} from 'react';
import {
  View,
  TouchableOpacity,
  StyleSheet,
  Animated,
  LayoutChangeEvent,
} from 'react-native';
import {useAppTheme, Text} from 'tsun-smart-ui';

type Props<T extends string> = {
  value: T;
  onChange: (value: T) => void;
  buttons: Array<{
    value: T;
    label: string;
  }>;
  className?: string;
};

const Segmented = <T extends string>({
  value,
  onChange,
  buttons,
  className,
}: Props<T>) => {
  const theme = useAppTheme();
  const selectedIndex = buttons.findIndex(button => button.value === value);
  const slideAnim = useRef(new Animated.Value(selectedIndex)).current;
  const [containerWidth, setContainerWidth] = useState(0);

  // 当选中项变化时，执行动画
  useEffect(() => {
    Animated.spring(slideAnim, {
      toValue: selectedIndex,
      useNativeDriver: true,
      friction: 8,
      tension: 50,
    }).start();
  }, [selectedIndex, slideAnim]);

  // 获取容器宽度
  const onLayout = (event: LayoutChangeEvent) => {
    const {width} = event.nativeEvent.layout;
    setContainerWidth(width);
  };

  // 计算每个按钮的宽度
  const buttonWidth = (containerWidth - 4) / buttons.length;

  return (
    <View
      className={`flex-row rounded-full  overflow-hidden w-full ${className}`}
      style={[
        styles.container,
        {backgroundColor: theme.colors?.background?.disabled},
      ]}
      onLayout={onLayout}>
      <View className="relative">
        {containerWidth > 0 && (
          <Animated.View
            style={[
              styles.animatedBackground,
              {
                backgroundColor: theme.colors?.neutral?.white,
              },
              {
                width: buttonWidth, // 减去内边距
                transform: [
                  {
                    translateX: slideAnim.interpolate({
                      inputRange: buttons.map((_, i) => i),
                      outputRange: buttons.map((_, i) => i * buttonWidth),
                      extrapolate: 'clamp',
                    }),
                  },
                ],
              },
            ]}
          />
        )}
      </View>

      {buttons.map((button, index) => {
        const isSelected = button.value === value;
        return (
          <TouchableOpacity
            key={button.value}
            onPress={() => onChange(button.value)}
            className={`flex-1 items-center justify-center`}
            style={[styles.button]}>
            <Text
              variant="cardTitle"
              style={{
                color: isSelected
                  ? theme.colors?.brand?.primary
                  : theme.colors?.neutral?.secondaryTitle,
              }}>
              {button.label}
            </Text>
          </TouchableOpacity>
        );
      })}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    height: 36,
    padding: 2,
  },
  button: {
    height: '100%',
    zIndex: 1,
  },
  animatedBackground: {
    position: 'absolute',
    height: 32, // 容器高度减去内边距
    borderRadius: 999,
    zIndex: 0,
  },
});

export default Segmented;
